#include <ws2tcpip.h>
#include <boost/asio.hpp>
//---------------------------------------------------------------------------------------------------------
// class add_source_membership_v4
// is for Windows Sockets 2 IPv4
// to set IP_ADD_SOURCE_MEMBERSHIP option.
//---------------------------------------------------------------------------------------------------------
class add_source_membership_v4
{
private:
    ip_mreq_source ipv4_value_{};

public:
    // Default constructor.
    // Construct with multicast address and IPv4 address specifying an interface.
    add_source_membership_v4(const boost::asio::ip::address_v4 &multicast_address,
        const boost::asio::ip::address_v4 &source_address,
        const boost::asio::ip::address_v4 &network_interface = boost::asio::ip::address_v4::any())
    {
        ipv4_value_.imr_multiaddr.s_addr =
            boost::asio::detail::socket_ops::host_to_network_long(multicast_address.to_uint());
        ipv4_value_.imr_sourceaddr.s_addr =
            boost::asio::detail::socket_ops::host_to_network_long(source_address.to_uint());
        ipv4_value_.imr_interface.s_addr =
            boost::asio::detail::socket_ops::host_to_network_long(network_interface.to_uint());
    }

    // Returns a value suitable for passing as the level argument to POSIX setsockopt() (or equivalent).
    template <typename Protocol>
    int level(const Protocol &) const noexcept
    {
        return BOOST_ASIO_OS_DEF(IPPROTO_IP);
    }

    // Returns a value suitable for passing as the option_name argument to POSIX setsockopt() (or equivalent).
    template <typename Protocol>
    int name(const Protocol &) const noexcept
    {
        return IP_ADD_SOURCE_MEMBERSHIP;
    }

    // Returns a pointer suitable for passing as the option_value argument to POSIX setsockopt() (or equivalent).
    template <typename Protocol>
    const void *data(const Protocol &) const noexcept
    {
        return &ipv4_value_;
    }

    // Returns a value suitable for passing as the option_len argument to POSIX setsockopt() (or equivalent),
    // after appropriate integer conversion has been performed.
    template <typename Protocol>
    std::size_t size(const Protocol &) const noexcept
    {
        return sizeof(ipv4_value_);
    }
};